from info import db
from . import profile_bp
from info.utils.common import user_login_data
from flask import render_template, g, current_app, request, jsonify
from info.response_code import RET
from info.utils.image_storage import pic_storage
from info import constants
from info.models import Category, News


# url:地址为 /profile/info
@profile_bp.route("/info")
@user_login_data
def user_center():
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }

    return render_template("profile/user.html", data=data)


# url:地址为 /profile/base_info
@profile_bp.route("/base_info", methods=["POST", "GET"])
@user_login_data
def base_info():
    # 查找用户信息
    user = g.user
    # 1判断是请求类型,如果是get的请求就获取个人用户信息,展示给页面
    if request.method == "GET":
        # 组织数据
        data = {
            "user_info": user.to_dict() if user else None
        }
        # 返回数据
        return render_template("profile/user_base_info.html", data=data)
    # 如果是POST请求,接受参数,进行操作
    else:
        # 1.接受参数 个性签名signature, 昵称nick_name, 性别gender, 用户对象user
        params_dict = request.json
        signature = params_dict.get("signature")
        nick_name = params_dict.get("nick_name")
        gender = params_dict.get("gender")
        # 2.检验参数:
        # 2.1 非空判断
        if not all([signature, nick_name, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # 2.2 性别是否在"MAN", 男 "WOMAN"  # 女
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # 3.根据用户对象,修改用户的信息
        if user:
            user.gender = gender
            user.nick_name = nick_name
            user.signature = signature
            try:
                db.session.commit()
            except Exception as result:
                db.session.rollback()
                current_app.logger.error(result)
                return jsonify(errno=RET.DBERR, errmsg="提交数据失败")
        # 4.返回值
        return jsonify(errno=RET.OK, errmsg="修改用户信息成功")


# url:地址为 /user/pic_info
@profile_bp.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_info():
    """修改头像"""
    # 查找用户信息
    user = g.user

    # 1.判断请求方式
    # 如果为GET请求,则直接返回数据
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("profile/user_pic_info.html", data=data)
    # 如果是POST请求,接受参数,进行操作
    else:
        # 1.获取参数avatar
        avatar = request.files.get("avatar")
        print(avatar)
        avatar_data = avatar.read()
        # 2.1非空判断
        if not avatar_data:
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # 2.2.用户是否登录
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
        # 3.1将图片数据保存到七牛云
        pic_name = None
        try:
            pic_name = pic_storage(avatar_data)
        except Exception as result:
            db.session.rollback()
            current_app.logger.error(result)
            return jsonify(errno=RET.DBERR, errmsg="提交数据失败")
        # 3.2将返回的图片名称保存到数据库
        user.avatar_url = pic_name
        try:
            db.session.commit()
        except Exception as result:
            db.session.rollback()
            current_app.logger.error(result)
            return jsonify(errno=RET.DBERR, errmsg="提交数据失败")
            # 4.返回值
        data = {
            "avatar_url": constants.QINIU_DOMIN_PREFIX + pic_name
        }
        return jsonify(errno=RET.OK, errmsg="修改用户信息成功", data=data)


# url:地址为 /profile/pass_info
@profile_bp.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    """修改密码"""
    # 1.获取参数 用户输入的原密码 用户修改的密码 获取用户对象
    user = g.user
    if request.method == "GET":
        return render_template("profile/user_pass_info.html")
    else:
        if user:
            params_dict = request.json
            old_password = params_dict.get("old_password")
            new_password = params_dict.get("new_password")
            # 2.参数校验
            # 2.1 非空校验
            if not all([old_password, new_password]):
                return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
            # 2.2 用户输入的原密码是否和数据库保存的密码一致
            if not user.check_passowrd(old_password):
                return jsonify(errno=RET.PARAMERR, errmsg="原密码错误")
                # 3.业务逻辑,修改用户密码
            user.password = new_password
            try:
                db.session.commit()
            except Exception as result:
                db.session.rollback()
                current_app.logger.error(result)
                return jsonify(errno=RET.DBERR, errmsg="修改密码异常")
            # 4.返回数据
            return jsonify(errno=RET.OK, errmsg="修改密码成功")


# url:地址为 /profile/collection
@profile_bp.route('/collection')
@user_login_data
def user_collection():
    """用户收藏列表"""
    # 1.获取用户对象, 获取页面的页数p
    user = g.user
    page = request.args.get("p", 1)

    # 2.1 参数校验,类型判断
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    # 3.0 根据user.collection_news查询对象进行分页查询

    if user:
        try:
            paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
            # 当前页的所有数据
            news_list = paginate.items
            # 当前的页面
            current_page = paginate.page
            # 总页面
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="收藏新闻查询失败")

    news_list_dict = []
    for news in news_list if news_list else []:
        news_list_dict.append(news.to_basic_dict())

        # 4.组织数据返回
    data = {
        "collections": news_list_dict,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template('profile/user_collection.html', data=data)


# url:地址为 /profile/news_release
@profile_bp.route('/news_release', methods=["POST", "GET"])
@user_login_data
def news_release():
    """用户新闻发布列表"""
    # 1. 判断请求方式
    user = g.user
    # 1.1 GET请求:
    if request.method == "GET":
        try:
            # 1.2 查去所有分类数据
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")
        # 1.3 将查取的分类对象列表转换成字典列表
        categorys_list = []
        for category in categorys if categorys else []:
            categorys_list.append(category.to_dict())
        # 1.4 将最新分类删除
        categorys_list.pop(0)

        data = {
            "categories": categorys_list
        }
        return render_template("profile/user_news_release.html", data=data)
    else:
        # 1.获取参数 新闻标题title 来源source  摘要digest 内容content 图片index_image_url  分类category_id  新闻状态status  新闻属于那个用户user_id
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        source = "个人发布"
        user = g.user
        # 2.参数校验
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
        # 3.创建新闻模型对象
        # 3.1 将新闻图片保存到七牛云
        index_image_data = None
        try:
            pic_name = index_image.read()
            index_image_data = pic_storage(pic_name)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="参数类型错误")
        # 3.2 创建新闻对象
        news = News()
        news.title = title
        news.digest = digest
        news.category_id = category_id
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + index_image_data
        news.content = content
        news.user_id = user.id
        news.source = source
        news.status = 1
        # 3.3 将新闻对象保存到数据库
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="新闻对象保存失败")

        return jsonify(errno=RET.OK, errmsg="新闻发布成功")


# url:地址为 /profile/news_list
@profile_bp.route('/news_list')
@user_login_data
def news_list():
    """用户新闻列表"""
    # 1.获取参数page,用户对象
    page = request.args.get("p", 1)
    print(page)
    user = g.user
    # 2.非空判断
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    new_list = []
    current_page = 1
    total_page = 1
    if user:
        # 3.业务逻辑,进行分页查询
        try:
            paginate = News.query.filter(News.user_id == user.id).order_by(News.create_time.desc()).paginate(page, 3,
                                                                                                             False)
            # 当前页新闻的数量
            new_list = paginate.items
            # 当前页码
            current_page = paginate.page
            # 总页数
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")
    # 将新闻对象列表转换为新闻字典列表
    new_list_dict = []
    for news in new_list if new_list else []:
        new_list_dict.append(news.to_review_dict())

    data = {
        "news_list": new_list_dict,
        "current_page": current_page,
        "total_page": total_page
    }
    print(data)
    return render_template("profile/user_news_list.html", data=data)
